package longcaisuyun.longcai.com.fragment;

import android.app.Fragment;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.zcx.helper.http.AsyCallBack;

import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import longcaisuyun.longcai.com.mystatic.publicstatic;
import longcaisuyun.longcai.com.net.Postchange;
import longcaisuyun.longcai.com.suyunbean.QiangDanItem;
import longcaisuyun.longcai.com.utils.Utils;
import longcaisuyun.longcai.com.yiliubabalongcaisuyun.GuangBoActivity;
import longcaisuyun.longcai.com.yiliubabalongcaisuyun.LimitAdapter;
import longcaisuyun.longcai.com.yiliubabalongcaisuyun.MyApplication;
import longcaisuyun.longcai.com.yiliubabalongcaisuyun.QiangResultAcitvity;
import longcaisuyun.longcai.com.yiliubabalongcaisuyun.R;
import wh.database.KJDB;


/**
 * Created by Administrator on 2016/2/18.
 */
public class frag_main_qiangdan extends Fragment implements AMapLocationListener {
    private AMapLocationClient locationClient = null;
    private AMapLocationClientOption locationOption = null;
    TextView tvReult;
    ImageView reflash;
    RelativeLayout l_location;
    AMapLocation loc;
    TextView tv_time;
    RelativeLayout r_result;
    Button button3;
    TextView tv_zhuangtai;
    ImageView wuliuicon;
    boolean isqiang = false;
    ListView qiang_list;
    private List<QiangDanItem> list = new ArrayList<>();
    private KJDB kjdb;
    Handler hand;
    LimitAdapter limitAdapter;

    public void setHand(Handler handler) {
        this.hand = handler;
    }

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = View.inflate(getActivity(), R.layout.frag_main_qiangdan, null);
        MyApplication.ScaleScreenHelper.loadView((ViewGroup) v);
        locationClient = new AMapLocationClient(getActivity().getApplicationContext());
        locationOption = new AMapLocationClientOption();
        // 设置定位模式为高精度模式
        locationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        locationClient.setLocationListener(this);
        kjdb = MyApplication.kjdb;

        IntentFilter filter = new IntentFilter(GuangBoActivity.action);
        getActivity().registerReceiver(broadcastReceiver, filter);

        ViewInit(v);

        initOption();
        // 设置定位参数
        locationClient.setLocationOption(locationOption);
        locationOption.setOnceLocation(false);
        // 启动定位
        locationClient.startLocation();
        mHandler.sendEmptyMessage(Utils.MSG_LOCATION_START);
        return v;
    }

    private void ViewInit(View v) {
        qiang_list = (ListView) v.findViewById(R.id.qiang_list);
        tv_zhuangtai = (TextView) v.findViewById(R.id.textView43);
        button3 = (Button) v.findViewById(R.id.button3);
        r_result = (RelativeLayout) v.findViewById(R.id.r_result);
        r_result.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getActivity().startActivity(new Intent(getActivity(), QiangResultAcitvity.class));

            }
        });
        wuliuicon = (ImageView) v.findViewById(R.id.imageView20);
        tvReult = (TextView) v.findViewById(R.id.tvReult);
        reflash = (ImageView) v.findViewById(R.id.reflash);
        tv_time = (TextView) v.findViewById(R.id.tv_time);
        limitAdapter = new LimitAdapter(getActivity(), list, kjdb);
        qiang_list.setAdapter(limitAdapter);
        button3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                MyApplication.myviewutil.startProgressDialog(getActivity());
                if (!isqiang) {
                    publicstatic.sijiType = "1";
                    new Postchange(MyApplication.myPreferences.readUid(), MyApplication.myPreferences.readProvinceId(), publicstatic.sijiType, new AsyCallBack<Postchange.Info>() {
                        public void onFail(String toast, int type) throws Exception {
                            super.onFail(toast, type);
                            MyApplication.myviewutil.stopProgressDialog();
                            Toast.makeText(getActivity(), "获取数据失败，请稍后尝试", Toast.LENGTH_SHORT).show();
                        }

                        @Override
                        public void onSuccess(String toast, int type, Postchange.Info info) throws Exception {
                            super.onSuccess(toast, type, info);
                            if (info.message.equals("0")) {
                                Toast.makeText(getActivity(), "获取数据失败，请稍后尝试", Toast.LENGTH_SHORT).show();
                                MyApplication.myviewutil.stopProgressDialog();
                            } else {
                                Log.i("message数据", info.message);
                                Toast.makeText(getActivity(), "您已进入抢单状态，请您随时留意抢单列表", Toast.LENGTH_SHORT).show();
                                tv_zhuangtai.setText("当前工作状态：等待接单/忙碌");
                                isqiang = true;
                                button3.setText("停止接单");
                                initData();
                                wuliuicon.setVisibility(View.GONE);
                                qiang_list.setVisibility(View.VISIBLE);
                                Message message = new Message();
                                message.what = 0;
                                hand.sendMessage(message);
                                MyApplication.myviewutil.stopProgressDialog();
                            }
                        }
                    }).execute(getActivity());
                } else {
                    publicstatic.sijiType = "2";
                    Message message = new Message();
                    message.what = 1;
                    hand.sendMessage(message);
                    isqiang = false;
                    tv_zhuangtai.setText("当前工作状态：已下班");
                    limitAdapter.stop();
                    button3.setText("开始接单");
                    wuliuicon.setVisibility(View.VISIBLE);
                    qiang_list.setVisibility(View.GONE);
                    Toast.makeText(getActivity(), "您已进入下班状态，可再次点击该按钮开始接单", Toast.LENGTH_SHORT).show();
                    MyApplication.myviewutil.stopProgressDialog();
                }
            }
        });
        reflash.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                initOption();
                // 设置定位参数
                locationClient.setLocationOption(locationOption);
                locationOption.setOnceLocation(false);
                // 启动定位
                locationClient.startLocation();
                mHandler.sendEmptyMessage(Utils.MSG_LOCATION_START);
            }
        });
        l_location = (RelativeLayout) v.findViewById(R.id.l_location);
        l_location.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!Utils.getLocationStr(loc).equals("")) {
                     Toast.makeText(getActivity(), Utils.getLocationStr(loc), Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    public void initData() {
        list.clear();
        List<QiangDanItem> datas = kjdb.findAll(QiangDanItem.class);
        for (int i = 0; i < datas.size(); i++) {
            list.add(datas.get(i));
        }
        limitAdapter.notifyDataSetChanged();
        limitAdapter.start();
    }

    public void reflash() {
        limitAdapter.stop();
    }

    public void initData_1(List<QiangDanItem> list_main) {
        if (!iscotain(list_main)) {
            for (int j = 0; j < list_main.size(); j++) {
                kjdb.save(list_main.get(j));
            }
        }
    }

    public boolean iscotain(List<QiangDanItem> list_main) {
        List<QiangDanItem> datas = kjdb.findAll(QiangDanItem.class);
        for (int j = 0; j < datas.size(); j++) {
            if (datas.get(j).getOrdernumber().equals(list_main.get(0).getOrdernumber())) {
                return true;
            }
        }
        return false;
    }

    public void onDestroy() {
        super.onDestroy();
        if (null != locationClient) {
            /**
             * 如果AMapLocationClient是在当前Activity实例化的，
             * 在Activity的onDestroy中一定要执行AMapLocationClient的onDestroy
             */
            locationClient.onDestroy();
            locationClient = null;
            locationOption = null;
        }
    }

    @Override
    public void onLocationChanged(AMapLocation arg0) {
        if (null != arg0) {
            Message msg = mHandler.obtainMessage();
            msg.obj = arg0;
            msg.what = Utils.MSG_LOCATION_FINISH;
            mHandler.sendMessage(msg);
        }
    }

    Handler mHandler = new Handler() {
        public void dispatchMessage(android.os.Message msg) {
            switch (msg.what) {
                //开始定位
                case Utils.MSG_LOCATION_START:
                    tvReult.setText("正在定位...");
                    break;
                // 定位完成
                case Utils.MSG_LOCATION_FINISH:

                    MyApplication.loc = loc = (AMapLocation) msg.obj;
                    System.out.println("坐标地址"+loc);
                    String result = Utils.getLocationStr(loc);
                    publicstatic.jingweidu = result;
                    System.out.println("******" + publicstatic.jingweidu);
                    tvReult.setText(result);
                    //存入首选项

                    MyApplication.myPreferences.saveAddress(result);
                    changeIp();
                    String getTime = getCurrentTime();
                    Date nowTime = new Date(System.currentTimeMillis());
                    SimpleDateFormat sdFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                    String retStrFormatNowDate = sdFormatter.format(nowTime);
                    tv_time.setText("更新时间：" + retStrFormatNowDate);
                    locationClient.stopLocation();
                    mHandler.sendEmptyMessage(Utils.MSG_LOCATION_STOP);

                    break;
                //停止定位
                case Utils.MSG_LOCATION_STOP:

                    break;
                default:
                    break;
            }
        }

        ;
    };

    private void initOption() {
        // 设置是否需要显示地址信息
        locationOption.setNeedAddress(true);
        locationOption.setOnceLocation(true);
        /**
         * 设置是否优先返回GPS定位结果，如果30秒内GPS没有返回定位结果则进行网络定位
         * 注意：只有在高精度模式下的单次定位有效，其他方式无效
         */
        locationOption.setGpsFirst(true);
        String strInterval = "1000";
        if (!TextUtils.isEmpty(strInterval)) {
            // 设置发送定位请求的时间间隔,最小值为1000，如果小于1000，按照1000算
            locationOption.setInterval(Long.valueOf(strInterval));
        }

    }


    private String getCurrentTime() {
        SimpleDateFormat format = new SimpleDateFormat("yy-MM-dd HH:mm:ss");
        return format.format(new java.util.Date());
    }

    public void changeIp() {

        new Postchange(MyApplication.myPreferences.readUid(), MyApplication.myPreferences.readProvinceId(), "1", new AsyCallBack<Postchange.Info>() {
            @Override
            public void onSuccess(String toast, int type, Postchange.Info info) throws Exception {
                super.onSuccess(toast, type, info);
            }

            @Override
            public void onFail(String toast, int type) throws Exception {
                super.onFail(toast, type);
            }
        }).execute(getActivity());
    }

    BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            // TODO Auto-generated method stub
//            textView.setText(intent.getExtras().getString("data"));
            limitAdapter.stop();
            limitAdapter.dele(intent.getExtras().getString("data"));
            limitAdapter.start();
        }
    };
}
